// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
 
 let audio =  cc.Class({
    extends: cc.Component,

    properties: {
        bgmId:null,
        sfxId:null,
    },

    init(){
        cc.game.on(cc.game.EVENT_HIDE,()=>{
            this.pauseAll();
        });
        cc.game.on(cc.game.EVENT_SHOW,()=>{
            this.resumeAll();
        });
    },
    play(fileName,isBGM = false){
        let fullName = this.getFullPath(fileName);
        let finishCb = ()=>{
           // if(!isBGM)
                this.sfxId = null;
        }
        if(isBGM)
        {
           this.bgmId =  cc.audioEngine.play(fullName,true);

        }
        else
        {
            this.sfxId = cc.audioEngine.play(fullName);
            cc.audioEngine.setFinishCallback(this.sfxId,finishCb);

        }
    },

    setVolume(volume = 0.5){
        // cc.audioEngine.setVolume(this.bgmId,volume);
        // if(volume <= 0)
        // {
        //     cc.audioEngine.stop(this.bgmId);
        // }
        if (this.bgmId >= 0) {
            if (volume > 0) {
                cc.audioEngine.resume(this.bgmId);
            }
            else {
                cc.audioEngine.pause(this.bgmId);
            }
            //cc.audioEngine.setVolume(this.bgmAudioID,this.bgmVolume);
            cc.audioEngine.setVolume(this.bgmId, volume);
        } 
    },

    getFullPath(filename){
        
        return cc.url.raw("resources/sounds/" + filename);
    },
    pauseAll: function () {
        cc.audioEngine.pauseAll();
    },

    resumeAll: function () {
        cc.audioEngine.resumeAll();
    }
});

module.exports = audio;